<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏大厅</title>
    <link rel="stylesheet" href="./css/common.css">
    <link rel="stylesheet" href="./css/game_hall.css">
    <style>
        /* 全局动画效果 */
        * {
            transition: all 0.3s ease;
        }

        body {
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            overflow-x: hidden;
            padding: 0;
            margin: 0;
        }

        .nav {
            height: 50px;
            line-height: 50px;
            text-align: center;
            font-size: 18px;
            padding: 0 15px;
            position: sticky;
            top: 0;
            z-index: 100;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            background-color: #fff;
        }

        .container {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            min-height: calc(100vh - 50px);
            padding: 20px 15px;
            box-sizing: border-box;
        }

        #screen {
            width: 100%;
            max-width: 500px;
            min-height: 200px;
            border-radius: 12px;
            text-align: left;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
            background-color: white;
        }

        .user-info h3 {
            text-align: center;
            margin-bottom: 20px;
            color: #333;
            font-size: 22px;
            font-weight: 600;
        }

        .user-info p {
            margin: 15px 0;
            font-size: 16px;
            line-height: 1.5;
        }

        .user-info strong {
            display: inline-block;
            width: 80px;
            color: #666;
        }

        .match-button {
            width: 100%;
            max-width: 500px;
            height: 50px;
            font-size: 18px;
            border-radius: 12px;
            margin-top: 10px;
            color: white;
            border: none;
            cursor: pointer;
            text-align: center;
            line-height: 50px;
            transition: all 0.2s ease;
        }
        
        #match-button {
            background-color: orange;
        }
        
        #match-weiqi-button {
            background: linear-gradient(to right, #4CAF50, #2E7D32);
        }
        
        #ai-button {
            background: linear-gradient(to right, #1e88e5, #0d47a1);
        }

        .match-button:active {
            transform: translateY(2px);
        }
        
        #match-button:active {
            background-color: #e59400;
        }
        
        #match-weiqi-button:active {
            background: linear-gradient(to right, #43A047, #1B5E20);
        }
        
        #ai-button:active {
            background: linear-gradient(to right, #1565c0, #0a3d8f);
        }

        /* 状态区域 */
        .status-area {
            width: 100%;
            max-width: 500px;
            text-align: center;
            margin-top: 20px;
            padding: 15px;
            font-size: 16px;
            background-color: #f8f8f8;
            border-radius: 10px;
            border: 1px solid #eee;
        }

        /* 消息提示 */
        .top-message {
            position: fixed;
            top: 60px;
            left: 50%;
            transform: translateX(-50%);
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 10px 25px;
            border-radius: 25px;
            z-index: 1000;
            max-width: 90%;
            text-align: center;
            animation: fadeInOut 3s forwards;
        }

        @keyframes fadeInOut {
            0% {
                opacity: 0;
                transform: translateX(-50%) translateY(-20px);
            }

            20% {
                opacity: 1;
                transform: translateX(-50%) translateY(0);
            }

            80% {
                opacity: 1;
                transform: translateX(-50%) translateY(0);
            }

            100% {
                opacity: 0;
                transform: translateX(-50%) translateY(-20px);
            }
        }

        /* 移动端特别优化 */
        @media (max-width: 480px) {
            .nav {
                font-size: 16px;
                height: 46px;
                line-height: 46px;
            }

            #screen {
                padding: 15px;
            }

            .user-info h3 {
                font-size: 20px;
                margin-bottom: 15px;
            }

            .user-info p {
                margin: 10px 0;
                font-size: 14px;
            }

            .match-button {
                font-size: 16px;
                height: 46px;
                line-height: 46px;
            }

            .status-area {
                font-size: 14px;
                padding: 12px;
            }

            .top-message {
                top: 50px;
                padding: 8px 20px;
                font-size: 14px;
            }
        }
    </style>
</head>

<body>
    <!-- 导航栏 -->
    <div class="nav">在线五子棋游戏大厅</div>

    <!-- 整个页面的容器元素 -->
    <div class="container">
        <div class="content-center">

            <!-- 展示用户信息 -->
            <div id="screen"></div>

            <!-- 五子棋匹配按钮 -->
            <div id="match-button" class="match-button">开始匹配</div>
            
            <!-- 人机对战按钮 -->
            <div id="ai-button" class="match-button">人机对战</div>

            <!-- 状态提示 -->
            <div class="status-area">状态: 等待中</div>
        </div>
    </div>

    <script src="./js/jquery.min.js"></script>
    <script>
        // 显示顶部消息（模拟连接成功提示）
        function showTopMessage(message) {
            const msg = document.createElement('div');
            msg.className = 'top-message';
            msg.textContent = message;
            document.body.appendChild(msg);

            setTimeout(() => {
                if (document.body.contains(msg)) {
                    document.body.removeChild(msg);
                }
            }, 3000);
        }


        // 后端交互逻辑
        var ws_url = "wss://" + location.host + "/hall";
        var ws_hdl = null;
        var button_flag = "stop"; // 五子棋匹配状态
        
        // 按钮引用
        var matchButton = document.getElementById("match-button");
        var weiqiMatchButton = document.getElementById("match-weiqi-button");
        var aiButton = document.getElementById("ai-button");
        var statusArea = document.querySelector(".status-area");

        // 断开连接主逻辑：页面完全卸载时关闭 WebSocket
        window.addEventListener('pagehide', (event) => {
            if (event.persisted === false && ws_hdl) {
                ws_hdl.close(1000);
                ws_hdl = null; // 避免重复关闭
            }
        });

        // 兜底 1：iOS 快速切换场景补充 visibilitychange
        document.addEventListener('visibilitychange', () => {
            if (document.visibilityState === 'hidden') {
                console.log("页面隐藏，连接保持");
            }
        });

        // 兜底 2：兼容低版本 IE 的降级方案
        if (!('onpagehide' in window)) {
            window.onbeforeunload = () => {
                if (ws_hdl) ws_hdl.close(1000);
            };
        }

        // 五子棋匹配按钮事件
        matchButton.onclick = function () {
            if (button_flag == "stop") {
                // 没有进行匹配的状态下点击按钮，发送对战匹配请求
                var req_json = { optype: "match_start" };
                ws_hdl.send(JSON.stringify(req_json));
            } else {
                // 正在匹配中的状态下点击按钮，发送停止对战匹配请求
                var req_json = { optype: "match_stop" };
                ws_hdl.send(JSON.stringify(req_json));
            }
        }

        // 人机对战按钮事件
        aiButton.onclick = function () {
             if (button_flag === "start") {
                showTopMessage('请先取消在线匹配');
                return;
            }
            var req_json = { optype: "match_ai" };
            ws_hdl.send(JSON.stringify(req_json));

            // 显示消息
            showTopMessage('正在开始五子棋人机对战');

            // 防止重复点击
            aiButton.disabled = true;
            setTimeout(() => {
                aiButton.disabled = false;
            }, 2000);
        }

        function get_user_info() {
            $.ajax({
                url: "/info",
                type: "get",
                success: function (res) {
                    var info_html =
                        '<div class="user-info">' +
                        '<h3>玩家信息</h3>' +
                        '<p><strong>用户名:</strong> ' + res.username + '</p>' +
                        '<p><strong>积分:</strong> ' + res.score + '</p>' +
                        '<p><strong>比赛场次:</strong> ' + res.total_count + '</p>' +
                        '<p><strong>获胜场次:</strong> ' + res.win_count + '</p>' +
                        '</div>';
                    document.getElementById("screen").innerHTML = info_html;

                    // 更新状态文本
                    statusArea.textContent = "状态: 未匹配";

                    // 建立WebSocket连接
                    ws_hdl = new WebSocket(ws_url);
                    ws_hdl.onopen = ws_onopen;
                    ws_hdl.onclose = ws_onclose;
                    ws_hdl.onerror = ws_onerror;
                    ws_hdl.onmessage = ws_onmessage;
                },
                error: function (xhr) {
                    alert(JSON.stringify(xhr));
                    location.replace("/login.html");
                }
            });
        }

        function ws_onopen() {
            console.log("websocket onopen");
            //showTopMessage('游戏大厅连接成功！');
        }

        function ws_onclose() {
            console.log("websocket onclose");
        }

        function ws_onerror() {
            console.log("websocket onerror");
            showTopMessage('网络连接错误');
        }

        function ws_onmessage(evt) {
            var rsp_json = JSON.parse(evt.data);
            if (rsp_json.result == false) {
                showTopMessage('重复登录！');
                location.replace("/login.html");
                return;
            }

            if (rsp_json["optype"] == "hall_ready") {
                showTopMessage('游戏大厅准备就绪!');
            }
            // 五子棋匹配成功
            else if (rsp_json["optype"] == "match_success") {
                showTopMessage('匹配成功，进入游戏房间！');
                location.replace("/game_room.html");
            }
            // 五子棋匹配开始
            else if (rsp_json["optype"] == "match_start") {
                console.log("玩家已经加入五子棋匹配队列");
                button_flag = "start";
                matchButton.innerHTML = "匹配中...点击按钮停止匹配";
                statusArea.textContent = "状态: 在线匹配中...";
            }
            // 五子棋匹配停止
            else if (rsp_json["optype"] == "match_stop") {
                console.log("玩家已经移除五子棋匹配队列");
                button_flag = "stop";
                matchButton.innerHTML = "开始在线匹配";
                statusArea.textContent = "状态: 未匹配";
            }
            else {
                alert(evt.data);
                location.replace("/login.html");
                return;
            }
        }

        // 初始化页面
        document.addEventListener('DOMContentLoaded', get_user_info);
    </script>
</body>
</html>